package com.github.mzule.fantasyslide.util;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by zhou on 2019-01-31.
 */

public class OkHttpUtil {
    public static Handler handler;


    public static void post(String url, Map<String,Object> map){
        final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url).build();
        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String errorMessage = e.getMessage();
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putString("errorMessage",errorMessage);
                msg.setData(data);
                handler.sendMessage(msg);

            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String responseData  = response.body().string();
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putString("responseData",responseData);
                msg.setData(data);
                handler.sendMessage(msg);

            }
        });
    }
}
